import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  Picker,
  DeviceEventEmitter,
  NativeAppEventEmitter
} from 'react-native';

import * as config from '../../constants/apiConfig';
import styles from './hkBindCardStyle';
import DatePicker from 'react-native-datepicker';
import moment from 'moment';
import api from '../../services/api';
import helper from '../util/helper';
import Toast from 'react-native-sk-toast';

import ToastTip from '../global/ToastTip';
import LoadingTip from '../global/LoadingTip';
import KeyboardAwareScrollView from '../global/keyboardScrollView/KeyboardAwareScrollView';
import CountDownText from '../global/countDown/CountDownText';
import Touch from '../global/Touch';

class ApprovedForm extends Component {
    constructor(props) {
		super(props);
        let {ownerinfo} = this.props;

		this.state = {
            isLoading: true,
			isRefreshing: false,
            textInputValue: "1",
            card_phone: ownerinfo.phone,
            card_addr: "",
            show_room_id: false,
            room_no_list: [],
            card_name: ownerinfo.name,
            btnDisabled: false
		};

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    async componentDidMount(){
        let {ownerinfo} = this.props;
        let res = await api.post("/account/findRoomInfoById",{id: ownerinfo.roomId});
        let { session } = this.props;
        let showRoom = true;

        if(res.cd == 0){
            let res = await api.post("/account/findRoomInfoById",{id: ownerinfo.roomId});
            if(session && session.user && session.user.homeUnit){
                 let unitArr = session.user.homeUnit.split(",");
                 let units = res.data.homeBuilding+"-"+res.data.homeUnit;
                 for (var i = 0; i < unitArr.length; i++) {
                     // 有楼层分割
                     if(unitArr[i].indexOf('[') != -1 && unitArr[i].indexOf(']') != -1 && unitArr[i].substring(0, unitArr[i].indexOf('[')) == units){
                         showRoom = false;
                         break;
                     }
                 }
            }

            var result = await api.post('/account/listRoomNo',{city:res.data.city,
                                                            homeNeighbourhoods:res.data.homeNeighbourhoods,
                                                            homeBuilding: res.data.homeBuilding,
                                                            homeUnit:res.data.homeUnit, page:0, pagesize: 1000});

            this.setState({
                card_addr: res.data.roomNo,
                show_room_id: showRoom,
                room_no_list: result.data
            });
        }
    }

    async _submitAction(){
        let {card_name, card_cd, card_no, card_phone, card_addr, textInputValue} = this.state;
        let {ownerinfo} = this.props;

        if(!card_name){
            this.refs.toast.show('请输入正确的用户姓名');
            return;
        }

        if(card_name.length>20){
            this.refs.toast.show('用户姓名不能超过20个字符');
            return;
        }

        if(card_no && !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(card_no)){
            this.refs.toast.show('请输入正确的身份证号码');
            return;
        }

        if(!card_phone){
            this.refs.toast.show('请输入手机号');
            return;
        }

        if(!/^1[0-9]{10}$/.test(card_phone)){
            this.refs.toast.show('请输入正确的手机号');
            return;
        }

        this.setState({loadingShow:true, btnDisabled: true});
        let res = await api.post("/account/app/approve",{id: ownerinfo.id,
                                                        role: textInputValue,
                                                        name: card_name,
                                                        idcardNumber: card_no,
                                                        roomNo: card_addr,
                                                        phone: card_phone});

        console.log("###", res);
        this.setState({loadingShow:false});

        if(res.cd == 1){
            this.refs.toast.show(res.msg);
        }else {
            this.refs.toast.show('审核通过', 800, ()=>{
                this.props.navigator.pop();
                let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
                Emitter.emit('owner.onload');
                Emitter.emit('approve.onload');
                this.setState({btnDisabled: false});
            });
        }

    }

    _selectPerson(){

    }

    componentWillUnmount(){
        let {dispatch, actions} = this.props;

        // dispatch(actions.card.card_name_change(''));
        // dispatch(actions.card.card_province_change(''));
        // dispatch(actions.card.card_city_change(''));
    }

    render() {
        let {room_no_list, show_room_id} = this.state;

        return (
            <View style={[styles.wrapper,{backgroundColor:'#f3f3f3'}]}>
                <KeyboardAwareScrollView style={[styles.container,{marginBottom:50}]} extraScrollHeight={60}>
                    <View style={styles.addressContainer}>
                        <Touch style={[styles.formItem, {justifyContent: 'space-between', paddingRight: 15}]} onPress={this._selectPerson.bind(this)}>
                            <Text style={styles.leftText}>成员类型</Text>
                            <Picker
                              style={{flex:1, marginLeft: 10, borderWidth:0, color: "#565656"}}
                              prompt={'请选择'}
                              selectedValue={this.state.textInputValue}
                              onValueChange={(val) => this.setState({textInputValue: val})}>
                              <Picker.Item label="业主" value="1" />
                              <Picker.Item label="租客" value="2" />
                              <Picker.Item label="员工" value="4" />
                            </Picker>
                        </Touch>

                        {show_room_id?
                        <Touch style={[styles.formItem, {justifyContent: 'space-between', paddingRight: 15}]}>
                            <Text style={styles.leftText}>房间号    </Text>
                            <Picker
                              style={{flex:1, marginLeft: 10, borderWidth:0, color: "#565656"}}
                              prompt={'请选择房间号'}
                              selectedValue={this.state.card_addr}
                              onValueChange={(val) => this.setState({card_addr: val})}>
                              {room_no_list.map((item)=>{
                                  return (<Picker.Item label={item} value={item} />)
                              })}
                            </Picker>
                        </Touch>:null}

                        <View style={styles.formItem}>
                            <Text style={styles.leftText}>用户姓名</Text>
                            <TextInput
                                value={this.state.card_name}
                                style={styles.itemRight}
                                editable = {true}
                                clearButtonMode={'while-editing'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请输入真实姓名'}
                                placeholderTextColor={'#B5B5B5'}
                                onChangeText={(text)=>{this.setState({card_name:text})}}
                            />
                        </View>
                        <View style={styles.formItem}>
                            <Text style={styles.leftText}>身份证号</Text>
                            <TextInput
                                value={this.state.card_no}
                                style={styles.itemRight}
                                editable = {true}
                                clearButtonMode={'while-editing'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'(选填)请输入身份证号码'}
                                placeholderTextColor={'#B5B5B5'}
                                onChangeText={(text)=>{this.setState({card_no:text})}}
                            />
                        </View>
                        <View style={[styles.formItem,{borderBottomWidth:0}]}>
                            <Text style={styles.leftText}>手机号    </Text>
                            <TextInput
                                value={this.state.card_phone}
                                style={[styles.itemRight,{color: "#565656"}]}
                                editable = {false}
                                keyboardType={'numeric'}
                                clearButtonMode={'while-editing'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请输入手机号'}
                                placeholderTextColor={'#B5B5B5'}
                                onChangeText={(text)=>{this.setState({card_phone:text})}}
                            />
                        </View>
                    </View>
                    <TouchableOpacity onPress={this._submitAction.bind(this)} disabled={this.state.btnDisabled} style={{backgroundColor:'#EA5404',marginRight:15, alignItems: 'center', marginTop:40,borderRadius: 2,marginLeft:15, height: 44, justifyContent: 'center', }}>
                        <Text style={styles.submitBtnText}>确定</Text>
                    </TouchableOpacity>
                </KeyboardAwareScrollView>

                <ToastTip ref="toast" offsetY={160}/>
                <LoadingTip show={this.state.loadingShow}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
ApprovedForm = connectHelper(state => state)(ApprovedForm);

module.exports = ApprovedForm;
